#include <sceneimporter.h>
#include <session.h>
#include <stdio.h>

#include <QDir>
#include <QFileInfo>
#include <QString>


SceneImporter::SceneImporter()
{
}


QString SceneImporter::ImportGroupNode(const QString &filename)
{
  QString projectFolder = Session::Get()->GetProjectFolder();
  if (filename.startsWith(projectFolder, Qt::CaseInsensitive))
    {
      // the file is aready within the project.
      // just chop of the project folder and we are done
      QString fn = filename;
      fn.replace(projectFolder, "", Qt::CaseInsensitive);
      return fn;
    }

  // group nodes get imported into the meshes folder
  QString meshesDestFolder = projectFolder + "/meshes/";

  // the same folder corresponds to the folder containing the xgroup file
  QFileInfo info (filename);
  QString meshesSrcFolder = info.absolutePath();

  // all the mesh files are located wihtin a subfolder with the same name
  // as the filename of the xgroup file
  QString subDir = info.completeBaseName();
  QString groupFileName = info.fileName();

  // now test if the dest file or the dest folder already exists
  QDir testFile (meshesDestFolder + "/" + groupFileName);
  QDir testFolder (meshesDestFolder + "/" + subDir);
  if (testFile.exists() || testFolder.exists())
    {
      // they already exist... so we cannot add it
      return QString::Null();
    }

  // create the subfolder where the mesh files will get stored
  QDir destDir (meshesDestFolder);
  if (!destDir.mkdir(subDir))
    {
      return QString::Null();
    }

  // scan all the source files
  QDir srcFolder (meshesSrcFolder + "/" + subDir);
  QFileInfoList files = srcFolder.entryInfoList();
  foreach (QFileInfo fi, files)
    {
      if (fi.isFile())
        {
          QFile::copy(fi.absoluteFilePath(), meshesDestFolder + "/" + subDir + "/" + fi.fileName());
        }
    }
  QFile::copy (filename, meshesDestFolder + "/" + groupFileName);

  QString fn = meshesDestFolder + "/" + groupFileName;
  fn.replace(projectFolder, "", Qt::CaseInsensitive);
  return fn;
}
